package com.entidades;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;

import android.annotation.SuppressLint;

import com.CustomClasses.FetchMySQL;
import com.CustomClasses.FetchXML;
import com.bolao.MainTabActivity;

enum mType{
	GROUP,
	ELIMINATORY;
}
public class Match {
	
	private static final String TEAM_B_SCORE = "teamBScore";
	private static final String TEAM_A_SCORE = "teamAScore";
	private static final String MATCHS_BETS_TABLE_NAME = "matchs_bets";
	private static final String MATCH_ID = "matchid";
	
	private static List<String> getList(){
		List<String> ls = new ArrayList<String>();
		ls.add(MATCH_ID);
		ls.add(TEAM_A_SCORE);
		ls.add(TEAM_B_SCORE);
		return ls;
	}
	private static final int NOT_PLAYED = -1;
	private static final String tagName = "match";
	private static final String[] fieldNames = new String[]{"id", "teams", "date", "time", "score", "is_group"};
	private int id;
	private mType mtype;
	private Team teamA,teamB;
	private Date date;
	private int scoreTA, scoreTB, scoreUserBetTA, scoreUserBetTB;
	private static List<Match> matches;
	
	private static final String idColumn = "matchid";
	
	private static final String teamAScore = TEAM_A_SCORE;
	
	private static final String teamBScore = TEAM_B_SCORE;
	
	private static final int LIST_ID = 0;
	
	private static final int LIST_TEAM = 1;
	
	private static final int LIST_DATE = 2;

	private static final int LIST_TIME = 3;
	
	private static final int LIST_SCORE = 4;
	
	//private static final String xmlFileName = "GroupMatchs.xml";
	
	private static final String URL = "http://www.worldcupcompendium.com/entities/GroupMatchs.xml";
	
	public int getScoreUserBetTB() {
		return scoreUserBetTB;
	}

	public void setScoreUserBetTB(int scoreUserBetTB) {
		this.scoreUserBetTB = scoreUserBetTB;
	}

	public int getScoreUserBetTA() {
		return scoreUserBetTA;
	}

	public void setScoreUserBetTA(int scoreUserBetTA) {
		this.scoreUserBetTA = scoreUserBetTA;
	}

	public int getId() {
		return id;
	}

	public boolean hasScore() {
		if(scoreTA!=NOT_PLAYED && scoreTB!=NOT_PLAYED) return true;
		else return false;
	}
	
	public boolean hasUserAnswer(){
		if(scoreUserBetTA!=NOT_PLAYED && scoreUserBetTB!=NOT_PLAYED) return true;
		else return false;
	}
	
	private HashMap<String, String> getUserMatchBet(){
		HashMap<String,String> hm = new HashMap<String,String>();
		hm.put(idColumn, String.valueOf(getId()));
		hm.put(teamAScore, String.valueOf(scoreUserBetTA));
		hm.put(teamBScore, String.valueOf(scoreUserBetTB));	
		return hm;
	}

	public static List<HashMap<String, String>> getAllUserMatchsBet(List<Match> list){
		
		List<HashMap<String, String>> hm = new ArrayList<HashMap<String,String>>();
		for(Match match: list){
			if(match.getScoreUserBetTA()>=0)
			hm.add(match.getUserMatchBet());
		}
		return hm;
	}

	
	Match(int id, Team a, Team b, boolean isGroup, Date date, int scoreA, int scoreB, int userScoreA, int userScoreB){
		this.id = id;
		setTeamA(a);
		setTeamB(b);
		if(isGroup) setMtype(mType.GROUP);
		else setMtype(mType.ELIMINATORY);
		this.setDate(date);
		this.setScoreTA(scoreA);
		this.setScoreTB(scoreB);	
		this.scoreUserBetTA = userScoreA;
		this.scoreUserBetTB = userScoreB;		
	}
	
	public static List<Match> getMatchOfTeams(List<Team> teamList){
		List<Match> ml = new ArrayList<Match>();
		for(Match m:getGroupMatchs()){			
			for(Team TA: teamList){
				if(m.getTeamA()==TA){
				for(Team TB: teamList){
					if(m.getTeamB()==TB){
						ml.add(m);
						}
					}
				}
			}
		}
		return ml;
	}
	
	public static List<Match> getMatchesOfTeam(Team team){
		List<Match> ml = new ArrayList<Match>();
		for(Match m: getGroupMatchs()){
			if(m.getTeamA() == team || m.getTeamB() == team){
				ml.add(m);
			}
		}
		DateComparator comparator = new DateComparator();
		Collections.sort(ml, comparator);
		return ml;
	}
	
	public Match getMatchById(int id){
		
		//REVER
		return matches.get(id);
	}
	
	public ResultType getResult(){
		if(scoreTA>scoreTB) return ResultType.WIN_TEAM_A;
		else if (scoreTA<scoreTB) return ResultType.WIN_TEAM_B;
		else if (scoreTA==NOT_PLAYED || scoreTB==NOT_PLAYED) return ResultType.NOT_PLAYED;
		else if (scoreTA==scoreTB) return ResultType.DRAWN;
		else return ResultType.NOT_PLAYED;

	}
	
	@SuppressLint("NewApi")
	public static List<Match> getGroupMatchs(){
		if(matches==null){
			matches = new ArrayList<Match>();
			
			try {
				
			List<HashMap<String, String>> listUa = new FetchMySQL(MATCHS_BETS_TABLE_NAME, getList(), MainTabActivity.getUser().getId()).execute().get();
		//	InputStream in = MainTabActivity.getAm().open(xmlFileName);
			
		//	List<List<String>> list = ReadXMLFile.parse(in, tagName, fieldNames);
			
			List<List<String>> list = new FetchXML().execute(URL, tagName, fieldNames).get();
			for(List<String> l: list){		
				
				String[] sTeams = l.get(LIST_TEAM).split(",");
				Integer matchId = Integer.valueOf(l.get(LIST_ID));

				String[] sDate = l.get(LIST_DATE).split("-");				
				Calendar cal = Calendar.getInstance();
			    cal.set(Calendar.YEAR, Integer.valueOf(sDate[2]));
			    cal.set(Calendar.MONTH, Integer.valueOf(sDate[1]));
			    cal.set(Calendar.DAY_OF_MONTH, Integer.valueOf(sDate[0]));			   
			    
				String[] sTime = l.get(LIST_TIME).split(":");
				cal.set(Calendar.HOUR_OF_DAY, Integer.valueOf(sTime[0]));
				cal.set(Calendar.MINUTE, Integer.valueOf(sTime[1]));
				
			    Date date = cal.getTime();
				
			    String score = l.get(LIST_SCORE);
			   
			    int scorea = NOT_PLAYED;
				int scoreb = NOT_PLAYED;
				int scoreUserA = NOT_PLAYED;
				int scoreUserB = NOT_PLAYED;
				for(HashMap<String, String> map: listUa){
					if(map.get(MATCH_ID).equals(String.valueOf(matchId))){
						scoreUserA = Integer.valueOf(map.get(TEAM_A_SCORE));
						scoreUserB = Integer.valueOf(map.get(TEAM_B_SCORE));
					}
				}
				
				
				
			    if(!score.isEmpty()){
			    	String scores[] = score.split(",");
			    	scorea = Integer.valueOf(scores[0]);
			    	scoreb = Integer.valueOf(scores[1]);
			    	
			    }
			    
				
				matches.add(new Match(
						matchId ,
						Team.getById(Integer.valueOf(sTeams[0])),
						Team.getById(Integer.valueOf(sTeams[1])),
						true, date, scorea, scoreb, scoreUserA, scoreUserB));
				
			}
			

			DateComparator comparator = new DateComparator();
			Collections.sort(matches, comparator);
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		return matches;
	}

	private static class DateComparator implements Comparator<Match> {
	    public int compare(Match match, Match otherMatch) {
	        return match.getDate().
	                compareTo(otherMatch.getDate());
	    }
	}
	
	
	public mType getMtype() {
		return mtype;
	}

	private void setMtype(mType mtype) {
		this.mtype = mtype;
	}

	public Team getTeamA() {
		return teamA;
	}

	private void setTeamA(Team teamA) {
		this.teamA = teamA;
	}

	public Team getTeamB() {
		return teamB;
	}

	private void setTeamB(Team teamB) {
		this.teamB = teamB;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public int getScoreTB() {
		return scoreTB;
	}

	public void setScoreTB(int scoreTB) {
		this.scoreTB = scoreTB;
	}

	public int getScoreTA() {
		return scoreTA;
	}

	public void setScoreTA(int scoreTA) {
		this.scoreTA = scoreTA;
	}
}
